
<script setup>import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showSuccessToast } from 'vant'
import { useUserStore } from '../stores/user.js'

const router = useRouter()
const userStore = useUserStore()

// 下拉刷新相关
const refreshing = ref(false)
const scrollTop = ref(0)

// 用户信息
const userInfo = ref(userStore.userInfo)

// 订单统计信息
const orderStats = ref({
  waiting: 0,
  pending: 0,
  completed: 0,
  cancelled: 0
})



// 就诊人数量
const patientCount = ref(0)

// 默认就诊人信息
const defaultPatient = ref(userStore.defaultPatient)

// 下拉刷新处理函数
const onRefresh = async () => {
  refreshing.value = true
  try {
    // 实际刷新操作 - 获取用户信息
    await fetchUserInfo()

    // 获取订单统计信息
    await fetchOrderStats()

    // 获取就诊人数量
    await fetchPatientCount()

    // 只在下拉刷新时显示成功提示
    showSuccessToast('刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    // showFailToast('刷新失败') // 如果需要错误提示可以取消注释
  } finally {
    refreshing.value = false
  }
}

// 获取用户信息
const fetchUserInfo = () => {
  return new Promise((resolve) => {
    // 这里应该调用实际的API获取用户信息
    // 示例模拟API调用
    setTimeout(() => {
      userInfo.value = userStore.userInfo
      resolve()
    }, 500)
  })
}

// 获取订单统计信息
const fetchOrderStats = () => {
  return new Promise((resolve) => {
    // 这里应该调用实际的API获取订单统计信息
    // 示例模拟API调用
    setTimeout(() => {
      orderStats.value = {
        all: 10,
        pending: 3,
        completed: 5,
        cancelled: 2
      }
      resolve()
    }, 300)
  })
}

// 获取就诊人数量
const fetchPatientCount = () => {
  return new Promise((resolve) => {
    // 这里应该调用实际的API获取就诊人数量
    // 示例模拟API调用
    setTimeout(() => {
      patientCount.value = 2
      resolve()
    }, 200)
  })
}

const showPatientInfo = () => {
  // 获取默认就诊人信息
  const defaultPatient = userStore.defaultPatient;

  // 添加空值检查
  if (defaultPatient && defaultPatient.patient_id) {
    // 跳转到 patientManagement 页面并传递患者ID
    router.push({
      path: '/patientManagement',
      query: {
        patientId: defaultPatient.patient_id
      }
    });
  }
};

// 页面数据初始化（不显示刷新提示）
const initData = async () => {
  try {
    await fetchUserInfo()
    await fetchOrderStats()
    await fetchPatientCount()
  } catch (error) {
    console.error('数据初始化失败:', error)
  }
}

// 跳转到指定页面
const goToPage = (path) => {
  router.push(path)
}

// 退出登录
const logout = () => {
  userStore.$reset()
  showSuccessToast('已退出登录')
  router.push('/login')
}

// 个人用户信息
const showUserInfo = () => {
  router.push('/userInfo')
}

// 更换手机号
const changePhone = () => {
  router.push('/changePhone')
}

// 修改密码
const changePassword = () => {
  router.push('/resetPassword')
}

// 页面加载时获取用户信息（不显示刷新提示）
onMounted(() => {
  initData()
})
</script>

<template>
  <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      class="personal-center-wrapper"
  >
    <div class="personal-center">
      <!-- 顶部用户信息 -->
      <div class="user-header" @click="showUserInfo">
        <div class="user-info">
          <van-image
              round
              width="60px"
              height="60px"
              :src="userInfo.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
              class="user-avatar"
          />
          <div class="user-details">
            <div class="user-name">{{ userInfo.username }}</div>
            <div class="user-phone">{{ userInfo.phone }}</div>
          </div>
        </div>
        <van-icon name="arrow" class="arrow-icon" />
      </div>

      <!-- 订单状态 -->
      <div class="order-section">
        <div class="section-header">
          <span>我的挂号</span>

        </div>
        <div class="order-stats">
          <div class="stat-item" @click="goToPage('/registrationHistory?status=all')">
            <van-icon name="orders-o" size="24px" />
            <div>待支付({{ orderStats.waiting }})</div>
          </div>
          <div class="stat-item" @click="goToPage('/registrationHistory?status=pending')">
            <van-icon name="pending-payment" size="24px" />
            <div>已支付({{ orderStats.pending }})</div>
          </div>
          <div class="stat-item" @click="goToPage('/registrationHistory?status=completed')">
            <van-icon name="checked" size="24px" />
            <div>已完成({{ orderStats.completed }})</div>
          </div>
          <div class="stat-item" @click="goToPage('/registrationHistory?status=cancelled')">
            <van-icon name="close" size="24px" />
            <div>已取消({{ orderStats.cancelled }})</div>
          </div>
        </div>
      </div>

      <!-- 就诊人管理 -->
      <div class="patient-section">
        <div class="section-header">
          <span>就诊人管理</span>
          <div class="more" @click="goToPage('/patientManagement')">
            全部就诊人({{ userStore.userInfo.count }})
            <van-icon name="arrow" />
          </div>
        </div>
        <!-- 默认就诊人 -->
        <div class="patient-list">
          <div
              class="patient-item"
              @click="showPatientInfo"
              v-if="defaultPatient"
          >
            <van-icon name="user-o" size="20px" />
            <div class="patient-info">
              <div class="patient-name">{{ defaultPatient.name || '未设置' }}</div>
              <div class="patient-id">{{ defaultPatient.id_card || '未设置' }}</div>
            </div>
            <van-icon name="arrow" />
          </div>
          <div v-else class="patient-item" @click="goToPage('/patientManagement')">
            <van-icon name="user-o" size="20px" />
            <div class="patient-info">
              <div class="patient-name">未设置默认就诊人</div>
              <div class="patient-id" @click="goToPage('/patientManagement')">点击前往设置</div>
            </div>
            <van-icon name="arrow" />
          </div>
        </div>

      </div>

      <!-- 快捷功能 -->
      <div class="quick-actions">
        <div
            class="action-item"
            @click="goToPage('/register?tab=1')"
        >
          <van-icon name="orders-o" size="24px" />
          <div>门诊缴费</div>
        </div>
        <div
            class="action-item"
            @click="goToPage('/billing')"
        >
          <van-icon name="balance-list-o" size="24px" />
          <div>费用清单</div>
        </div>
        <div
            class="action-item"
            @click="changePassword"
        >
          <van-icon name="lock" size="24px" />
          <div>修改密码</div>
        </div>
        <div
            class="action-item"
            @click="goToPage('/customerService')"
        >
          <van-icon name="service-o" size="24px" />
          <div>在线客服</div>
        </div>
        <div
            class="action-item"
            @click="goToPage('/settings')"
        >
          <van-icon name="setting-o" size="24px" />
          <div>设置</div>
        </div>
      </div>

      <!-- 退出登录 -->
      <div class="logout-section">
        <van-button
            type="default"
            block
            round
            @click="logout"
        >
          退出登录
        </van-button>
      </div>
    </div>
  </van-pull-refresh>
</template>

<style scoped>.personal-center-wrapper {
  height: 100vh;
  overflow: hidden;
}

.personal-center {
  padding-bottom: 20px;
  min-height: 100vh;
}

.user-header {
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  padding: 20px 16px;
  display: flex;
  align-items: center;
  color: white;
}

.user-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.user-avatar {
  margin-right: 15px;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}

.user-phone, .user-points {
  font-size: 14px;
  opacity: 0.9;
}

.arrow-icon {
  font-size: 18px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 16px 10px;
  font-size: 16px;
  font-weight: bold;
}

.more {
  font-size: 14px;
  font-weight: normal;
  color: #999;
  display: flex;
  align-items: center;
}

.order-stats {
  display: flex;
  padding: 10px 0;
  background: white;
  margin-bottom: 10px;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  font-size: 12px;
  color: #666;
}

.stat-item :deep(.van-icon) {
  margin-bottom: 5px;
}

.patient-section {
  background: white;
  margin-bottom: 10px;
}

.patient-list {
  padding: 0 16px;
}

.patient-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.patient-item:last-child {
  border-bottom: none;
}

.patient-info {
  margin-left: 10px;
  flex: 1;
}

.patient-name {
  font-size: 16px;
  margin-bottom: 5px;
}

.patient-id {
  font-size: 12px;
  color: #999;
}

.add-patient {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px 0;
  color: #1989fa;
  font-size: 14px;
}

.security-section {
  background: white;
  margin-bottom: 10px;
}

.security-list {
  padding: 0 16px;
}

.security-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.security-item:last-child {
  border-bottom: none;
}

.security-label {
  flex: 1;
  font-size: 16px;
  color: #333;
}

.security-value {
  font-size: 14px;
  color: #999;
  margin-right: 10px;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  background: white;
  padding: 20px 0;
  margin-bottom: 10px;
}

.action-item {
  text-align: center;
  padding: 10px 0;
  font-size: 12px;
  color: #666;
}

.action-item :deep(.van-icon) {
  margin-bottom: 8px;
}

.logout-section {
  padding: 0 16px;
}
</style>
